<template>
  <div class="admin-management">
    <!-- 添加管理员按钮和搜索区域 -->
    <div class="search-area">
      <el-button type="primary" @click="showAddDialog">添加管理员+</el-button>
      <div class="search-inputs">
        <el-input v-model="searchParams.adminName" placeholder="请输入管理员姓名" clearable
          style="width: 200px; margin-right: 10px;" />
        <el-input v-model="searchParams.phone" placeholder="请输入管理员电话" clearable
          style="width: 200px; margin-right: 10px;" />
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div>

    <!-- 管理员表格 -->
    <el-table :data="pagedAdmins" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="cadreId" label="管理员编号" />
      <el-table-column prop="name" label="管理员姓名" />
      <el-table-column prop="gender" label="性别">
        <template #default="{ row }">
          {{ row.gender === 'M' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" />
      <el-table-column prop="idCard" label="身份证号" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" @click="showEditDialog(row)">修改</el-button>
          <el-button type="text" style="color: #f56c6c;" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalAdmins"
        :page-sizes="[5, 10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 添加/编辑管理员对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" :before-close="handleCloseDialog">
      <el-form :model="adminForm" label-width="100px">
        <el-form-item label="管理员姓名" required>
          <el-input v-model="adminForm.name" />
        </el-form-item>
        <el-form-item label="性别" required>
          <el-radio-group v-model="adminForm.gender">
            <el-radio label="M">男</el-radio>
            <el-radio label="F">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" required>
          <el-input v-model="adminForm.phone" />
        </el-form-item>
        <el-form-item label="身份证号" required>
          <el-input v-model="adminForm.idCard" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="adminForm.roleId" placeholder="请选择角色" size="small" style="width: 240px">
            <el-option v-for="item in roles" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminTables, updateAdminTables, addAdminTables, deleteAdminTables } from '@/api/admin'
import { getRoles } from "@/api/role"
// onMounted  queryAdmin   620
// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
// 表格需要展示的数据对象数组
const pagedAdmins = ref([])
// 条件搜索参数
const searchParams = reactive({
  adminName: '',
  phone: "",
  currentPage: currentPage.value,
  pageSize: pageSize.value
})

// 分页的总记录数
const totalAdmins = ref(0)
// 查询当前表格中的数据
const queryAdmin = () => {
  getAdminTables(searchParams).then((res) => {
    if (res.code == 2000) {
      pagedAdmins.value = res.data
      totalAdmins.value = res.total
    } else {
      pagedAdmins.value = []
      totalAdmins.value = 0
    }
  })
}
// 页面加载的时候，直接就调用后台，获取表格中的数据
queryAdmin()

let roles = ref([])
// 弹窗中查询角色
const loadRoles = () => {
  getRoles().then(res => {
    if (res.code == 2000) {
      roles.value = res.data
    }

  })
}

// 对话框相关状态
const dialogVisible = ref(false)
const isEditing = ref(false)
const dialogTitle = computed(() => isEditing.value ? '修改管理员信息' : '添加管理员')

// 管理员表单
const adminForm = reactive({
  cadreId: '',
  name: '',
  gender: 'M',
  phone: '',
  idCard: '',
})

// 显示添加对话框
const showAddDialog = () => {
  loadRoles()
  isEditing.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  isEditing.value = true
  Object.assign(adminForm, JSON.parse(JSON.stringify(row)))
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(adminForm, {
    name: '',
    gender: 'M',
    phone: '',
    idCard: '',
  })
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
}

// 确认添加/编辑
const handleConfirm = () => {
  // 简单验证
  if (!adminForm.name || !adminForm.phone || !adminForm.idCard) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (isEditing.value) {
    // 更新管理员
    if (isEditing.value) {
      updateAdminTables(adminForm).then(res => {
        if (res.code == 2000) {
          ElMessage.success('修改成功')
          handleSearch() // 重新筛选数据
        }
      })

    }
  } else {
    addAdminTables(adminForm).then(res => {
      if (res.code == 2000) {
        ElMessage.success('添加成功')
        handleSearch() // 重新筛选数据
      }
    })
  }
  dialogVisible.value = false
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('是否确认删除该管理员?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteAdminTables(row.cadreId).then(res => {
      ElMessage.success('删除成功')
      handleSearch() // 重新筛选数据
    })

  })
}

// 处理状态变更
const handleStatusChange = (row) => {
  ElMessage.success(`管理员 ${row.adminName} 状态已${row.status === 'active' ? '启用' : '禁用'}`)
}

// 处理搜索
const handleSearch = () => {
  queryAdmin()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  searchParams.pageSize = val
  queryAdmin()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  searchParams.currentPage = val
  queryAdmin()
}

</script>

<style scoped>
.admin-management {
  padding: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-inputs {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.el-button--text {
  padding: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>